package it.amicosmanettone.whatsimage;

import java.util.List;

import it.amicosmanettone.whatsimage.adapter.MainGridAdapter;
import it.amicosmanettone.whatsimage.client.ApiClient;
import it.amicosmanettone.whatsimage.jsonbean.Category;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.util.Log;
import android.util.LruCache;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	public static LruCache<String, Bitmap> mMemoryCache=null;

	
	public static List<Category> CURRENT_CATEGORY_LIST=null;
	public static int CATEGORY_DEEP=0;//Livello di navigazione...
	static GridView listCategories = null;
	static MainGridAdapter adapter = null;

	private static int RESULT_LOAD_IMAGE = 1;
	View topLevelLayout;
	View bottomLevelLayout;

	String nameOfCategory = null;
	int POSITION;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		this.topLevelLayout = findViewById(R.id.main_top_layout);
		this.bottomLevelLayout = findViewById(R.id.main_bottom_layout);
		bottomLevelLayout.setEnabled(false);
		
		if (isFirstTime()) {
			
        	topLevelLayout.setVisibility(View.INVISIBLE);
        	
        }else{
        	
        	topLevelLayout.setVisibility(View.INVISIBLE);
        	
        }
		
		
		if (mMemoryCache == null) {
			final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
			Log.v("CACHE", "Memoria disponibile per cache: " + maxMemory);
			final int cacheSize = maxMemory / 8;
			if (Configuration.IMAGE_MEMORY_CACHE_ACTIVE) {
				mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
					@Override
					protected int sizeOf(String key, Bitmap bitmap) {
						return bitmap.getByteCount() / 1024;
					}
				};
			}// End if...
		}

		Bundle extras = getIntent().getExtras();

		/******************** BOTTONI ********************/

		Button buttonUpload = (Button) findViewById(R.id.main_button_upload);
		Button buttonKarma = (Button) findViewById(R.id.main_button_credits);
		String oldTextKarma = buttonKarma.getText().toString();

		final Long userCredits = ApiClient.API_GetUserCredit().getCredit();
		buttonKarma.setText(oldTextKarma + " " + userCredits);
		
		buttonKarma.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {

				String title = getText(R.string.alert_title).toString();
				String text = getText(R.string.alert_text_karma).toString();
				String myKarma = getText(R.string.alert_text_myKarma).toString();
				String buttonOk = getText(R.string.alert_button_ok).toString();
				
				AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
				alert.setTitle(title);
				
				TextView message = new TextView(MainActivity.this);
				message.setTextSize(30);
				message.setPadding(15, 15, 15, 15);
				message.setText(text + "\n\r\n\r" + myKarma + " " + userCredits);
				message.setGravity(Gravity.CENTER_HORIZONTAL);
				
				alert.setView(message);
				alert.setCancelable(false);

				alert.setNeutralButton(buttonOk, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						
						
						

					}// End onClick
					
				});// End of voteButton

				AlertDialog alertDialog = alert.create();
				
						
						alertDialog.show();
				

			}
		});

		buttonUpload.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {

				Intent gallery = new Intent(
						Intent.ACTION_PICK,
						android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

				startActivityForResult(gallery, RESULT_LOAD_IMAGE);
				overridePendingTransition(R.xml.translate_in, R.xml.translate_out);

			}
		});

		/******************** CATEGORIE ********************/

		if (extras != null) {

			this.nameOfCategory = extras.getString("nameOfCategory");

		}

		if (nameOfCategory == null) {
			CATEGORY_DEEP=0;
			

			adapter = new MainGridAdapter(getApplicationContext(),
					R.layout.row_main);
			listCategories = (GridView) findViewById(R.id.main_grid);
			listCategories.setAdapter(adapter);
			

			this.CURRENT_CATEGORY_LIST = ApiClient.API_GetCatalogue().getCategory();
			adapter.addAll(CURRENT_CATEGORY_LIST);
			

			listCategories.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {


					if (ApiClient.API_GetCatalogue().getCategory()
							.get(position).getLeaf() == null) {
						
						Intent imageList = new Intent(getApplicationContext(), ImagesActivity.class);
						imageList.putExtra("categoryLabel", ApiClient.API_GetCatalogue().getCategory().get(position).getCategoryLabel());
						startActivity(imageList);
						overridePendingTransition(R.xml.translate_in, R.xml.translate_out);

					} else {
						
						String nameOfCategory = ApiClient.API_GetCatalogue().getCategory().get(position).getCategoryName();
						Intent refresh = new Intent(getApplicationContext(),MainActivity.class);
						refresh.putExtra("nameOfCategory", nameOfCategory);
						refresh.putExtra("POSITION", position);
						startActivity(refresh);
						overridePendingTransition(R.xml.translate_in, R.xml.translate_out);

					}
				}

			});

		} else {

			this.setTitle(nameOfCategory);
			this.POSITION = extras.getInt("POSITION");

			listCategories = (GridView) findViewById(R.id.main_grid);

			adapter = new MainGridAdapter(getApplicationContext(),
					R.layout.row_main);

			listCategories.setAdapter(adapter);
			List<Category> newCategoryList=ApiClient.API_GetCatalogue().getCategory().get(POSITION).getLeaf();
			CURRENT_CATEGORY_LIST=newCategoryList;
			adapter.addAll(newCategoryList);
			CATEGORY_DEEP++;
			listCategories.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {

					// selected item
					String nameOfCategory = ApiClient.API_GetCatalogue()
							.getCategory().get(position).getLeaf().get(position).getCategoryName();

					Log.v("GRID_CLICK", "Category name: " + nameOfCategory);

					Intent refresh = new Intent(getApplicationContext(),
							MainActivity.class);

					refresh.putExtra("nameOfCategory", nameOfCategory);
					refresh.putExtra("POSITION", position);
					startActivity(refresh);
					overridePendingTransition(R.xml.translate_in, R.xml.translate_out);

				}

			});

		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		getMenuInflater().inflate(R.menu.main, menu);
		/*SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
		String userLogged = sharedPref.getString("userLogged", "GUEST");
		
		if(userLogged.equals("GUEST")){
			menu.removeItem(R.id.action_logout);
		}else{
			menu.removeItem(R.id.action_login);
		}*/
		menu.removeItem(R.id.action_login);
		menu.removeItem(R.id.action_logout);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		case android.R.id.home:
			
			onBackPressed();

			return true;
			
		case R.id.action_info:
			
			Intent informationActivity = new Intent(this, InformationActivity.class);
			startActivity(informationActivity);
			overridePendingTransition(R.xml.translate_in, R.xml.translate_out);

			return true;
			
		case R.id.action_login:
			Intent loginActivity = new Intent(this, LoginActivity.class);
			loginActivity.putExtra("fromActivity", "MAIN");
			startActivity(loginActivity);
			overridePendingTransition(R.xml.translate_in, R.xml.translate_out);
			
			return true;
		
		case R.id.action_logout:
			Intent logoutActivity = new Intent(this, LoginActivity.class);
			logoutActivity.putExtra("fromActivity", "MAIN");
			startActivity(logoutActivity);
			overridePendingTransition(R.xml.translate_in, R.xml.translate_out);
			
			return true;
			
		}
		
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onBackPressed() {
		if(CATEGORY_DEEP==0){
		String text = getText(R.string.main_dialog_exit).toString();
		String buttonY = getText(R.string.main_dialog_YES).toString();
		String buttonN = getText(R.string.main_dialog_NO).toString();

		new AlertDialog.Builder(this)
				.setMessage(text)
				.setCancelable(false)
				.setPositiveButton(buttonY,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								MainActivity.this.finish();
							}
						}).setNegativeButton(buttonN, null).show();
		}else{
			MainActivity.this.finish();
			CATEGORY_DEEP--;
		}
	}// End onBackPressed

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
				&& null != data) {
			Uri selectedImage = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };

			Cursor cursor = getContentResolver().query(selectedImage,
					filePathColumn, null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			String picturePath = cursor.getString(columnIndex);
			cursor.close();

			Log.v("PATH_IMG", picturePath);
			Toast.makeText(getApplicationContext(),
					"PERCORSO IMMAGINE " + picturePath, Toast.LENGTH_LONG)
					.show();
			/*
			 * ImageView imageView = (ImageView) findViewById(R.id.imgView);
			 * imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
			 */

		}
		
		

	}
	
	private boolean isFirstTime() {

		SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);;
		boolean ranBefore = preferences.getBoolean("RanBefore", false);
		if (!ranBefore) {

			SharedPreferences.Editor editor = preferences.edit();
			editor.putBoolean("RanBefore", true).commit();
			topLevelLayout.setVisibility(View.VISIBLE);
			
			topLevelLayout.setOnTouchListener(new View.OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					topLevelLayout.setVisibility(View.INVISIBLE);
					
					return false;
				}

			});

		}
		return ranBefore;

	}

}
